//
//  MobileVerifyViewController.m
//  51易借
//
//  Created by apple on 2017/9/19.
//  Copyright © 2017年 张睿. All rights reserved.
//

#import "MobileVerifyViewController.h"
#import "MobileAgreementViewController.h"
#import "UIWebViewController.h"

@interface MobileVerifyViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *mobileField;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;
@property (weak, nonatomic) IBOutlet UITextField *verifyField;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (nonatomic, strong)NSTimer * countDownTimer;


@property (nonatomic, assign)NSInteger count;

@end
static NSInteger  secondsCountDown = 60;
@implementation MobileVerifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.count = 0;
    
    NSString * telString = DEF_GET_OBJECT(@"tel");
    self.mobileField.text = telString;
    self.mobileField.delegate = self;
    
    [self setupNavBar];
    [self sentMobile];
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    return NO;
}

- (void)setupNavBar{
    [self setupForDismissKeyboard];
    self.title = @"手机运营商";
    self.topView.backgroundColor = TOTAL_COLOR;

    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}


- (void)backToLastView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)codeTask:(UIButton *)sender {
    [self.view endEditing:YES];
    if(self.mobileField.text.length == 0)
    {
        [self showHint:@"请输入手机号"];
        return;
    }
    if(![self isMobileNumber:self.mobileField.text])
    {
        [self showHint:@"手机号码不正确"];
    }
    
    self.codeBtn.enabled = NO;
    secondsCountDown = 60;
    
    [self setupDownTimer];
    


}







- (void)setupDownTimer{
    
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
}


//定时器的方法
- (void)countDownAction{
    
    secondsCountDown --;
    
    [self.codeBtn setTitle:[NSString stringWithFormat:@"%lds后重新获取",(long)secondsCountDown] forState:UIControlStateDisabled];
    
    //当倒计时到0时做需要的操作，button变成可选状态
    if(secondsCountDown == 0){
        
        [_countDownTimer invalidate];
        
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.codeBtn.enabled = YES;
    }
}

- (IBAction)agreeTask:(UIButton*)sender {
    sender.selected = !sender.selected;


}

- (IBAction)agreementTask:(UIButton *)sender {
    
//    MobileAgreementViewController * vc = [MobileAgreementViewController new];
//    vc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:vc animated:YES];
    HIDDEN_TAB;
    
    UIWebViewController * webVC = [UIWebViewController new];
    
    webVC.count = @"5";
    
    [self.navigationController pushViewController:webVC animated:YES];
}

- (IBAction)sureTask:(UIButton *)sender {
    if(self.mobileField.text.length == 0)
    {
        [self showHint:@"请输入手机号"];
        return;
    }
    if(![self isMobileNumber:self.mobileField.text])
    {
        [self showHint:@"手机号码不正确"];
    }
    if(self.pwdField.text.length == 0)
    {
        [self showHint:@"请输入服务密码"];
        return;

    }
//    if(self.verifyField.text.length == 0)
//    {
//        [self showHint:@"请输入验证码"];
//        return;
//    }
//    [self verifyFirstComplete:^{
//        
//        
//        
//        [self verifysecondComplete:^(NSString*result){
//            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
//                                                                           message:result
//                                                                    preferredStyle:UIAlertControllerStyleAlert];
//            
//            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
//                                                                  handler:^(UIAlertAction * action) {
//                                                                      //响应事件
//                                                                      
//                                                                  }];
//            
//            [alert addAction:defaultAction];
//            [self presentViewController:alert animated:YES completion:nil];
//
//        }];
//    }];
    
    
        
    ParaModel * para = [ParaModel new];
    
    para.netServicePwd = self.pwdField.text;
    para.dynamicPwd = self.verifyField.text;
    
//    NSLog(@"==%@",[para toDictionary]);
    
    [[NetworkTool manager] POST:[Interfacefile collectDatasource] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        
//        NSLog(@"two==%@",responseObject);
        
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
            //                complete([responseObject objectForKey:@"data"]);
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"认证中"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }else if([[responseObject objectForKey:@"code"]intValue]==5016)
        {
            if (self.verifyCodeConstraint.constant == 50) {
                
                [self showHint:[responseObject objectForKey:@"message"]];
            }else{
                
                self.verifyCodeConstraint.constant = 50;
                //                    complete([responseObject objectForKey:@"data"]);
            }
            
            
        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        
//        NSLog(@"error==%@",error);
//        
//        [self showHint:@"网络错误"];
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"网络错误"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                  [self.navigationController popViewControllerAnimated:YES];
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }];
   
}

-(void)sentMobile{
    
    ParaModel * para = [ParaModel new];
    
    
    [[NetworkTool manager] POST:[Interfacefile applyToGetReceipt] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        
//                NSLog(@"one==%@",responseObject);
        
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
            
        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        [self showHint:@"网络错误"];
    }];
}

-(void)verifyFirstComplete:(void(^)())complete
{
    ParaModel * para = [ParaModel new];
    
    
    [[NetworkTool manager] POST:[Interfacefile applyToGetReceipt] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        
//        NSLog(@"one==%@",responseObject);
        
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
            complete();
        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        [self showHint:@"网络错误"];
    }];
    
}

-(void)verifysecondComplete:(void(^)(NSString*result))complete
{
    ParaModel * para = [ParaModel new];
    
    para.netServicePwd = self.pwdField.text;
    para.dynamicPwd = self.verifyField.text;
    
    
    
    [[NetworkTool manager] POST:[Interfacefile collectDatasource] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        
        NSLog(@"two==%@",responseObject);
        
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
            complete([responseObject objectForKey:@"data"]);
            
        }else if([[responseObject objectForKey:@"code"]intValue]==5016)
        {
            if (self.verifyCodeConstraint.constant == 50) {
                
                [self showHint:[responseObject objectForKey:@"message"]];
            }else{
                
                self.verifyCodeConstraint.constant = 50;
                complete([responseObject objectForKey:@"data"]);
            }
            

        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        [self showHint:@"网络错误"];
    }];
    
}



//正则表达式判断手机号是否正确
- (BOOL)isMobileNumber:(NSString *)mobileNum {
    
    //    电信号段:133/149/153/180/181/189/173/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170/171
    
    NSString *MOBILE = @"^1(3[0-9]|4[579]|5[0-35-9]|8[0-9]|7[0136-8])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
}

@end
